﻿using Lost_and_Found.Models.ObjectManager;
using Lost_and_Found.Models.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace Lost_and_Found.Controllers
{
    public class AccountController : Controller
    {
        public ActionResult Login()
        {
            if (Request.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                UserManager userManager = new UserManager();
                if (userManager.ValidateUser(model))
                {
                    FormsAuthentication.SetAuthCookie(model.Username, false);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("Index", "Home");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Tên đăng nhập hoặc mật khẩu không đúng");
                }
            }
            return View();
        }



        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult Register()
        {
            if (Request.IsAuthenticated)
            {
                return RedirectToAction("Index", "Home");
            }
                return View();
        }



        [HttpPost]
        public ActionResult Register(RegisterModel user)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    UserManager userManager = new UserManager();
                    if (!userManager.IsUserLoginIDExist(user.Username))
                    {
                        userManager.Add(user);
                        FormsAuthentication.SetAuthCookie(user.Username, false);
                        return RedirectToAction("index", "Home");
                    }
                    else
                    {
                        ModelState.AddModelError("", "LogID already taken");
                    }
                }
            }
            catch
            {
                return View(user);
            }

            return View(user);
        }

    }
}
